﻿using JNPF.Basics.Models;
using JNPF.Data;
using JNPF.Data.Util;
using JNPF.Utils;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 订单管理
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017-12-11
    /// </summary>
    internal class OrderService : DataFactory, OrderIService
    {
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<OrderEntity>> GetList(PageInput input)
        {
            using (var db = this.Basic)
            {
                var userInfo = UserProvider.Instance.Get();
                var queryWhere = ExtLinq.True<OrderEntity>();
                var queryParam = input.queryJson.ToObject();
                //关键字（订单编码、客户名称、业务人员）
                if (!input.keyword.IsEmpty())
                {
                    var keyword = input.keyword.ToString();
                    queryWhere = queryWhere.And(m => m.OrderCode.Contains(keyword) || m.CustomerName.Contains(keyword) || m.SalesmanName.Contains(keyword));
                }
                //起始日期-结束日期
                if (!queryParam["startTime"].IsEmpty() && !queryParam["endTime"].IsEmpty())
                {
                    var startTime = CommonHelper.GetDateTime(queryParam["startTime"].ToString());
                    var endTime = CommonHelper.GetDateTime(queryParam["endTime"].ToString());
                    startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 0, 0, 0, 0);
                    endTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59, 999);
                    queryWhere = queryWhere.And(t => t.OrderDate >= startTime && t.OrderDate <= endTime);
                }
                //数据权限过滤
                if (!userInfo.IsAdministrator)
                {
                    queryWhere = queryWhere.And(new AuthorizeBll().GetCondition<OrderEntity>(userInfo, ModuleIdEnum.Extend_Order));
                }
                return await db.GetIQueryable<OrderEntity>().Where(queryWhere).OrderByDescending(t => t.CreatorTime).GetPageResultAsync(input);
            }
        }
        /// <summary>
        /// 子列表（订单明细）
        /// </summary>
        /// <param name="id">主表Id</param>
        /// <returns></returns>
        public async Task<List<OrderEntryEntity>> GetOrderEntryList(string id)
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<OrderEntryEntity>().Where(m => m.OrderId == id).OrderBy(o => o.SortCode).ToListAsync();

            }
        }
        /// <summary>
        /// 子列表（订单收款）
        /// </summary>
        /// <param name="id">主表Id</param>
        /// <returns></returns>
        public async Task<List<OrderReceivableEntity>> GetOrderReceivableList(string id)
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<OrderReceivableEntity>().Where(m => m.OrderId == id).OrderBy(o => o.SortCode).ToListAsync();
            }
        }
        /// <summary>
        /// 信息（前单、后单）
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="method">方法:prev、next</param>
        /// <returns></returns>
        public async Task<OrderEntity> GetPrevOrNextInfo(string id, string method)
        {
            using (var db = this.Basic)
            {
                var orderEntity = await db.GetEntityAsync<OrderEntity>(m => m.Id == id);
                var userInfo = UserProvider.Instance.Get();
                var queryWhere = ExtLinq.True<OrderEntity>();
                if (!userInfo.IsAdministrator)
                {
                    queryWhere = queryWhere.And(new AuthorizeBll().GetCondition<OrderEntity>(userInfo, ModuleIdEnum.Extend_Order));
                }
                if (method == "prev")
                {
                    queryWhere = queryWhere.And(m => m.CreatorTime > orderEntity.CreatorTime);
                    var data = (await db.GetListAsync(queryWhere)).OrderBy(o => o.CreatorTime).FirstOrDefault();
                    return data;
                }
                else
                {
                    queryWhere = queryWhere.And(m => m.CreatorTime < orderEntity.CreatorTime);
                    var data = (await db.GetListAsync(queryWhere)).OrderByDescending(o => o.CreatorTime).FirstOrDefault();
                    return data;
                }

            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<OrderEntity> GetInfo(string id)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<OrderEntity>(m => m.Id == id);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">订单信息</param>
        public async Task Delete(OrderEntity entity)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();
                await db.DeleteAsync<OrderEntity>(m => m.Id == entity.Id);
                await db.DeleteAsync<OrderEntryEntity>(m => m.OrderId == entity.Id);
                await db.DeleteAsync<OrderReceivableEntity>(m => m.OrderId == entity.Id);
                await db.CommitTransactionAsync();
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">订单信息</param>
        /// <param name="orderEntryList">订单明细</param>
        /// <param name="orderReceivableList">订单收款</param>
        public async Task Create(OrderEntity entity, List<OrderEntryEntity> orderEntryList, List<OrderReceivableEntity> orderReceivableList)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();
                await db.InsertAsync(entity);
                await db.InsertAsync(orderEntryList);
                await db.InsertAsync(orderReceivableList);
                await db.CommitTransactionAsync();
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">订单信息</param>
        /// <param name="orderEntryList">订单明细</param>
        /// <param name="orderReceivableList">订单收款</param>
        public async Task Update(OrderEntity entity, List<OrderEntryEntity> orderEntryList, List<OrderReceivableEntity> orderReceivableList)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();
                await db.UpdateAsync(entity);
                await db.DeleteAsync<OrderEntryEntity>(m => m.OrderId == entity.Id);
                await db.DeleteAsync<OrderReceivableEntity>(m => m.OrderId == entity.Id);
                await db.InsertAsync(orderEntryList);
                await db.InsertAsync(orderReceivableList);
                await db.CommitTransactionAsync();
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="orderEntity">订单信息</param>
        public async Task<int> Update(OrderEntity orderEntity)
        {
            using (var db = this.Basic)
            {
                return await db.UpdateAsync(orderEntity);
            }
        }
    }
}